package com.lolaage.tsr.dals.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 
 * @author dengpeng
 * 2013-6-19 上午10:29:26
 */
public class ContextUtil implements ApplicationContextAware, InitializingBean {

	private static ApplicationContext context;
	//注入配置文件的路径,从ClassPath开始。
	private static Map<String, Object> initConfig = new HashMap<String, Object>();
	
	public void setApplicationContext(ApplicationContext appliactionContext)
			throws BeansException {
		context = appliactionContext;
	}
	
	public static ApplicationContext getApplicationContext() {
		return context;
	}

	public synchronized void afterPropertiesSet() throws Exception {
		//读取系统初始化配置文件，因为读取了硬盘文件，所以需要做线程同步。
		loadConfig("jdbc.properties");
		try {
			loadConfig("otherconfig.properties");
		} catch (Exception e) {
		}
	}
	
	public void loadConfig(String path) {
		//读取系统初始化配置文件，因为读取了硬盘文件，所以需要做线程同步。
		InputStream in = null;
		Properties prop;
		try {
			in = this.getClass().getClassLoader().getResourceAsStream(path);
			prop  = new Properties();
			prop.load(in);
		} catch (IOException e) {
			throw new RuntimeException("在读取配置文件时发生错误！请确认配置的路径正确！");
		}
		finally{
			try {
				if(in!=null)
					in.close();
			} catch (IOException e) {
				throw new RuntimeException("在读取配置文件时发生错误！请确认文件没有被占用！");
			}
		}
		if (prop != null) {
			Set<Object> keys =  prop.keySet();
			for(Object obj : keys)
			{
				String key = obj.toString();
				initConfig.put(key, prop.get(key));
			}
		}
	}
//	public static Map<String, Object> getInitConfig() {
//		return initConfig;
//	}
	public static String getInitConfig(String key) {
		Object val = initConfig.get(key);
		return val != null ? val.toString() : null;
	}
	public static void put(String key,Object value) {//手动设置配置值时用,如执行脚本的时候把定时任务都关闭 timer.open = false
		initConfig.put(key, value);
	}
	public static <T> T getBean(Class<T> clazz) {
		return context.getBean(clazz);
	}
	public static Object getBean(String beanName) {
		return context.getBean(beanName);
	}

	public static Object getBean(String beanName, Class<?> requireType) {
		return context.getBean(beanName, requireType);
	}

	public static boolean containsBean(String beanName) {
		return context.containsBean(beanName);
	}
	
	public static boolean isSingleton(String beanName) {
		return context.isSingleton(beanName);
	}
	
	public static Class<?> getType(String beanName) {
		return context.getType(beanName);
	}
	
	public static String[] getAliases(String beanName) {
		return context.getAliases(beanName);
	}
}
